package com.septagon.wildtunnel.model;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.AsyncTask;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class GetThreadListTask extends AsyncTask<String, Integer, ArrayAdapter<String>> {

	private ArrayAdapter<String> array;
	private ListView  listView;
	private List<Thread> lists;
	
	public GetThreadListTask(ArrayAdapter<String> array,ListView lv){
		super();
		this.array = array;
		this.listView = lv;
	}
	
	@Override
	protected ArrayAdapter<String> doInBackground(String... arg0) {
		String url = arg0[0];
		HttpClient hc = new HttpClient();
		String data = hc.httpGetString(url + "subject.txt");
		Pattern thread = Pattern.compile("(\\d{9,10})[.]dat<>(.+) [(](\\d{1,5})[)]");
		List<com.septagon.wildtunnel.model.Thread> list = new ArrayList<com.septagon.wildtunnel.model.Thread>();
		for (String item : data.split("\n")) {
			Matcher m = thread.matcher(item);
			if (m.find()){
				com.septagon.wildtunnel.model.Thread t = new com.septagon.wildtunnel.model.Thread();
				t.setName(m.group(2));
				t.setDatKey(m.group(1));
				t.setResCount(m.group(3));
				t.setUrl(url + "dat/" + m.group(1) + ".dat");
				array.add(t.getName());
				list.add(t);
			}
		}
		this.lists = list;
		return array;
	}    
	@Override
    protected void onPostExecute(ArrayAdapter<String> result) {
		this.listView.setAdapter(result);
		this.listView.setTag(this.lists);
    }

}
